package com.mata.worktime.controller.work;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mata.worktime.entity.BaseEntity;
import com.mata.worktime.entity.user.Role;
import com.mata.worktime.entity.user.User;
import com.mata.worktime.entity.work.Member;
import com.mata.worktime.service.user.RoleService;
import com.mata.worktime.service.user.UserService;
import com.mata.worktime.service.work.MemberService;
import com.mata.worktime.vo.LayuiTableVO;
import com.mata.worktime.vo.ResultVO;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import com.mata.worktime.controller.BaseController;
import com.mata.worktime.dto.PageParamDTO;
import com.mata.worktime.entity.user.Dept;
import com.mata.worktime.entity.work.Project;
import com.mata.worktime.enums.ResultEnum;
import com.mata.worktime.exception.BaseException;
import com.mata.worktime.service.user.DeptService;
import com.mata.worktime.service.work.ProjectService;

import java.util.*;

import static java.util.Comparator.comparingLong;
import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.toCollection;


/**
 * 项目控制器
 *
 * @author earthchen
 * @date 2018/9/29
 **/
@Controller
@RequestMapping("/project")
public class ProjectController extends BaseController {

    @Autowired
    private ProjectService projectService;

    @Autowired
    private MemberService memberService;

    @Autowired
    private DeptService deptService;

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;


    /**
     * 分页获取项目页面
     *
     * @param model 模型
     * @return 项目页面
     */
    @RequiresPermissions("system:project:view")
    @GetMapping("/view")
    public String project(Model model) {
        List<Dept> deptList = deptService.list(
                new QueryWrapper<Dept>().eq("status", "0").eq("del_flag", "0"));
        model.addAttribute("deptList", deptList);
        return "project/task";
    }

    /**
     * 跳转更新页面
     *
     * @param projectId 项目id
     * @param model     模型
     * @return 更新页面
     */
    @GetMapping("/update/{projectId}")
    public String updatePage(@PathVariable("projectId") Long projectId, Model model) {
        Project project = projectService.getById(projectId);
//        Dept dept = deptService.selectDeptById(Long.valueOf(project.getDeptId()));
//        model.addAttribute("dept", dept);
        model.addAttribute("project", project);
        model.addAttribute("isLeader", isLeader(new QueryWrapper<Project>()));
        return "project/update";
    }

    /**
     * 分页获取项目
     *
     * @param pageParamDTO 分页参数
     * @param projectName  项目名
     * @return 项目的layui table
     */
    @RequiresPermissions("system:project:list")
    @GetMapping("/list")
    @ResponseBody
    public LayuiTableVO list(PageParamDTO pageParamDTO, String projectName, String projectId) {
        IPage<Project> page1 = new Page<>(pageParamDTO.getPage(), pageParamDTO.getSize());
        IPage<Project> page2 = new Page<>(pageParamDTO.getPage(), pageParamDTO.getSize());
        QueryWrapper<Project> projectQueryWrapper = new QueryWrapper<Project>()
                .like(StringUtils.isNotBlank(projectName), "project_name", projectName)
                .like(StringUtils.isNotBlank(projectId), "project_id", projectId)
                .orderByDesc("update_time");
        int leader = isLeader(projectQueryWrapper);
//        if (isLeader(projectQueryWrapper)) {
//            projectQueryWrapper.eq("manager", getUserId());
//        }
        if (leader > 3 || leader == 2) {
            page1 = projectService.page(page1, projectQueryWrapper);
        }
        if (leader == 1) {
            projectQueryWrapper.eq("manager", getUserId().toString());
            page1 = projectService.page(page1, projectQueryWrapper);
        }
        if (leader == 3) {
            page1 = projectService.page(page1, projectQueryWrapper);
            page2 = projectService.page(page2, new QueryWrapper<Project>()
                    .like(StringUtils.isNotBlank(projectName), "project_name", projectName)
                    .like(StringUtils.isNotBlank(projectId), "project_id", projectId)
                    .orderByDesc("update_time")
                    .eq("manager", getUserId().toString()));//查询项目经理所拥有的项目
            page1.getRecords().addAll(page2.getRecords());
            //去重
            List<Project> collect = page1.getRecords().stream().collect(
                    collectingAndThen(
                            toCollection(() -> new TreeSet<>(comparingLong(BaseEntity::getId))), ArrayList::new)
            );
            page1.getRecords().clear();
            page1.setRecords(collect);
            page1.setTotal(page1.getRecords().size());
        }
        return getTableInfo(page1);

    }

    // 判断是否为 项目经理 或者 部门经理
    public int isLeader(QueryWrapper<Project> projectQueryWrapper) {
        // 为1时，只是项目经理   为2时 只是部门经理   为 3时 既是项目经理又是部门经理
        int isLeader = 0;
        List<Role> roles = roleService.selectRolesByUserId(getUserId());
        List<Long> deptIdList = new ArrayList<>();
        for (Role role : roles) {
            if (role.isFlag()) {
                if (role.getRoleName().equals("项目经理")) {
                    isLeader += 1;
                }
                if (role.getRoleName().equals("部门经理")) {
                    deptService.getAllChildrenDept(getUser().getDeptId()).forEach(dept -> deptIdList.add(dept.getId()));
                    projectQueryWrapper.in("dept_id", deptIdList);
                    isLeader += 2;
                }
                if (role.getRoleName().equals("管理员")) {
                    isLeader += 4;
                }
            }
        }
        return isLeader;
    }

    /**
     * 根据id获取当前项目信息
     *
     * @param projectId 项目id
     * @return 统一结果
     */
    @GetMapping("/{projectId}")
    @ResponseBody
    public ResultVO getById(@PathVariable("projectId") Long projectId) {
        return ResultVO.success(projectService.getById(projectId));
    }

    /**
     * 增加项目
     *
     * @param project 项目信息
     * @return 统一结果
     */
    @RequiresPermissions("system:project:add")
    @PostMapping("/add")
    @ResponseBody
    public ResultVO add(Project project) {
        if (project.getStartDate().getTime() > project.getEndDate().getTime()) {
            throw new BaseException(ResultEnum.PROJECT_STARTDATE_MUST_LT_ENDDATE);
        }
        project.setCreateBy(getLoginName());
        List<Project> projectList = projectService.list(
                new QueryWrapper<Project>()
                        .eq(StringUtils.isNotBlank(project.getProjectName()), "project_name", project.getProjectName())
                        .eq("del_flag", 0)
                        .or()
                        .eq(StringUtils.isNotBlank(project.getProjectId()), "project_id", project.getProjectId())
                        .eq("del_flag", 0)
        );
        if (!projectList.isEmpty()) {
            throw new BaseException(ResultEnum.PROJECT_NAME_OR_PROJECTID_ALEARLY_HAVE);
        }
        project.setUpdateTime(new Date());
        return ResultVO.success(projectService.save(project));
    }

    /**
     * 修改项目
     *
     * @param project 项目信息
     * @return 统一返回结果
     */
    @RequiresPermissions("system:project:edit")
    @PutMapping("/update/{id}")
    @ResponseBody
    public ResultVO update(@PathVariable("id") Long id, Project project) {
        if (project.getStartDate().getTime() > project.getEndDate().getTime()) {
            throw new BaseException(ResultEnum.PROJECT_STARTDATE_MUST_LT_ENDDATE);
        }
        List<Project> projectList = projectService.list(
                new QueryWrapper<Project>()
                        .eq(StringUtils.isNotBlank(project.getProjectName()), "project_name", project.getProjectName())
                        .eq("del_flag", 0)
                        .ne("id", project.getId())
//                .or()
//                .eq(StringUtils.isNotBlank(project.getProjectId()),"project_id", project.getProjectId())
//                .eq("del_flag",0)
        );
        if (!projectList.isEmpty()) {
            throw new BaseException(ResultEnum.PROJECT_NAME_OR_PROJECTID_ALEARLY_HAVE);
        }
        project.setId(id);
        project.setUpdateTime(new Date());
        return ResultVO.success(projectService.updateById(project));
    }

    /**
     * 删除指定id的项目
     *
     * @param projectId 项目id
     * @return 统一结果
     */
    @RequiresPermissions("system:project:delete")
    @DeleteMapping("/del/{projectId}")
    @ResponseBody
    public ResultVO del(@PathVariable("projectId") Long projectId) {
        return ResultVO.success(projectService.removeById(projectId));
    }

    /**
     * 分页获取用户
     *
     * @param pageParamDTO 分页参数
     * @return 项目的layui table
     */
    @RequiresPermissions("system:project:list")
    @GetMapping("/users")
    @ResponseBody
    public LayuiTableVO users(PageParamDTO pageParamDTO) {
        IPage<User> page = new Page<>(pageParamDTO.getPage(), pageParamDTO.getSize());
        QueryWrapper<User> queryWrapper = new QueryWrapper<User>();
        queryWrapper.ne("login_name", "admin");
        queryWrapper.eq("del_flag", "0");
        page = userService.page(page, queryWrapper);
        return getTableInfo(page);
    }

    /**
     * 分页获取项目中用户
     *
     * @param pageParamDTO 分页参数
     * @param projectId    项目id
     * @return 项目的layui table
     */
    @RequiresPermissions("system:project:list")
    @GetMapping("/userList")
    @ResponseBody
    public LayuiTableVO userList(PageParamDTO pageParamDTO, long projectId) {
        IPage<Member> page = new Page<>(pageParamDTO.getPage(), pageParamDTO.getSize());
        page = memberService.page(page,
                new QueryWrapper<Member>()
                        .eq(StringUtils.isNotBlank(projectId + ""), "pro_id", projectId)
                        .orderByDesc("join_time")
                        .select("user_id", "user_name", "pro_id", "join_time")
        );
        return getTableInfo(page);

    }

    /**
     * 分页获取不在项目中用户
     *
     * @param pageParamDTO 分页参数
     * @param projectId    项目id
     * @return 项目的layui table
     */
    @RequiresPermissions("system:project:list")
    @GetMapping("/userOutList")
    @ResponseBody
    public LayuiTableVO userOutList(PageParamDTO pageParamDTO, long projectId, String manager) {
        IPage<User> page = new Page<>(pageParamDTO.getPage(), pageParamDTO.getSize());
        List<Member> memberIdList = memberService.list(new QueryWrapper<Member>()
                .eq(StringUtils.isNotBlank(projectId + ""), "pro_id", projectId)
                .select("user_id"));
        QueryWrapper<User> queryWrapper = new QueryWrapper<User>();
        // 去掉超级管理员要把 admin 改成  超级管理员 或   把 user_name 改成 login_name
        queryWrapper.ne("login_name", "admin");
        queryWrapper.ne("id", Long.parseLong(manager));
        queryWrapper.eq("del_flag", "0");
        memberIdList.forEach(memberId -> queryWrapper.ne("id", Long.parseLong(memberId.getUserId())));
        page = userService.page(page, queryWrapper);
        return getTableInfo(page);
    }

    /**
     * 添加用户到项目
     *
     * @param userId    用户id
     * @param projectId 项目id
     * @param userName  用户昵称
     * @return 统一结果
     */
    @RequiresPermissions("system:project:add")
    @PostMapping("/addMember")
    @ResponseBody
    public ResultVO addMember(String userId, long projectId, String userName) {
        Member member = new Member();
        member.setUserId(userId);
        member.setProId(projectId);
        member.setUserName(userName);
        return ResultVO.success(memberService.save(member));
    }

    /**
     * 移除用户到项目
     *
     * @param userId    用户id
     * @param projectId 项目id
     * @return 统一结果
     */
    @RequiresPermissions("system:project:delete")
    @PostMapping("/remMember")
    @ResponseBody
    public ResultVO remMember(String userId, long projectId) {
        return ResultVO.success(memberService.remove(new UpdateWrapper<Member>()
                .eq("user_id", userId)
                .eq("pro_id", projectId)));
    }


    /**
     * 管理员批量移除指定id的用户(物理删除)
     *
     * @param idList    用户id列表
     * @param projectId 项目id
     * @return
     */
    @RequiresPermissions("system:project:delete")
    @PostMapping("/batch/remMember")
    @ResponseBody
    public ResultVO remMemberBatch(String[] idList, String projectId) {
        return ResultVO.success(memberService.deleteMemberByIds(idList, projectId));
    }

    /**
     * 管理员批量添加用户
     *
     * @param memberList 用户列表
     * @return
     */
    @RequiresPermissions("system:project:add")
    @PostMapping("/batch/addMember")
    @ResponseBody
    public ResultVO addMemberBatch(@RequestBody List<Member> memberList) {
        return ResultVO.success(memberService.saveBatch(memberList));
    }
}